import React, { useState, useRef, useEffect } from 'react'
import { clsx } from 'clsx'

// 角色类型定义
export type RoleType = 'emma' | 'sophie' | 'mike' | string

export interface RoleTrait {
  key: string
  value: string
}

export interface RoleOption {
  id: string
  name: string
  title?: string
  description: string
  icon?: string
  color?: string
  specialty?: string
  input_spec?: string
  output_spec?: string
  custom_traits?: RoleTrait[]
  systemPrompt: string
  system_prompt_snapshot?: string
  is_builtin?: boolean
  usage_count?: number
  last_used_at?: string
  modelConfig?: {
    model?: string
    temperature?: number
    maxTokens?: number
  }
}

export interface RolesData {
  builtin: RoleOption[]
  custom: RoleOption[]
  remaining?: number
  lastUsed?: string
}

// API调用函数
const fetchRoles = async (): Promise<RolesData> => {
  try {
    const response = await fetch('/api/roles', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data.success ? data : { builtin: [], custom: [] }
  } catch (error) {
    console.error('Failed to fetch roles:', error)
    return { builtin: [], custom: [] }
  }
}

interface RoleSelectorProps {
  currentRole: RoleType
  onRoleChange: (role: RoleType) => void
  onCreateRole?: () => void
  disabled?: boolean
  className?: string
}

export const RoleSelector: React.FC<RoleSelectorProps> = ({
  currentRole,
  onRoleChange,
  onCreateRole,
  disabled = false,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [rolesData, setRolesData] = useState<RolesData>({ builtin: [], custom: [] })
  const [loading, setLoading] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  // 获取当前角色信息
  const currentRoleOption = [...rolesData.builtin, ...rolesData.custom].find(role => role.id === currentRole)

  // 加载角色数据
  useEffect(() => {
    const loadRoles = async () => {
      setLoading(true)
      try {
        const data = await fetchRoles()
        setRolesData(data)
      } catch (error) {
        console.error('Failed to load roles:', error)
      } finally {
        setLoading(false)
      }
    }
    
    loadRoles()
  }, [])

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const getColorClasses = (color: string = 'gray') => {
    const colorMap = {
      blue: 'bg-blue-100 text-blue-700',
      purple: 'bg-purple-100 text-purple-700',
      pink: 'bg-pink-100 text-pink-700',
      green: 'bg-green-100 text-green-700',
      orange: 'bg-orange-100 text-orange-700'
    }
    return colorMap[color as keyof typeof colorMap] || 'bg-gray-100 text-gray-700'
  }

  const getRoleDisplayInfo = (role: RoleOption) => {
    if (role.is_builtin) {
      return {
        icon: role.icon || '🤖',
        description: role.description || '',
        specialty: role.specialty || '',
        badgeText: '专家',
        badgeColor: role.color || 'blue'
      }
    } else {
      return {
        icon: '⚡',
        description: role.title || role.description || (role.input_spec ? `输入：${role.input_spec.slice(0, 30)}...` : ''),
        specialty: role.output_spec ? `输出：${role.output_spec.slice(0, 30)}...` : '',
        badgeText: '自定义',
        badgeColor: 'purple'
      }
    }
  }

  return (
    <div className={clsx('relative', className)} ref={dropdownRef}>
      {/* 选择器按钮 */}
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className="flex items-center gap-3 px-4 py-2 rounded-lg border-2 bg-white transition-all hover:border-blue-300 hover:shadow-sm"
        style={{
          border: '2px solid var(--gray-200)',
          borderRadius: 'var(--radius-lg)',
          fontSize: 'var(--text-sm)'
        }}
      >
        {/* 角色信息 */}
        <div className="flex items-center gap-2">
          <span className="text-base">
            {currentRoleOption ? getRoleDisplayInfo(currentRoleOption).icon : '🤖'}
          </span>
          <span className="font-medium">
            {currentRoleOption?.name || '选择角色'}
          </span>
        </div>

        {/* 状态和箭头 */}
        <div className="flex items-center gap-2 ml-2">
          <span className="text-gray-400" style={{ fontSize: 'var(--text-xs)' }}>
            {isOpen ? '▲' : '▼'}
          </span>
        </div>
      </button>

      {/* 展开面板 */}
      {isOpen && (
        <div 
          className="absolute top-full mt-2 left-0 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-80"
          style={{
            borderRadius: 'var(--radius-lg)',
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)'
          }}
        >
          {loading ? (
            <div className="p-4 text-center">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600 mx-auto"></div>
              <p className="text-sm text-gray-500 mt-2">加载角色中...</p>
            </div>
          ) : (
            <>
              {/* 预设角色 */}
              {rolesData.builtin.length > 0 && (
                <div className="p-4 border-b border-gray-100">
                  <h4 className="font-semibold mb-3 text-gray-700" style={{ fontSize: 'var(--text-sm)' }}>
                    预设角色
                  </h4>
                  
                  <div className="space-y-2">
                    {rolesData.builtin.map(role => {
                      const displayInfo = getRoleDisplayInfo(role)
                      return (
                        <div
                          key={role.id}
                          onClick={() => {
                            onRoleChange(role.id)
                            setIsOpen(false)
                          }}
                          className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all ${
                            currentRole === role.id 
                              ? 'bg-blue-50 border-blue-200 border-2' 
                              : 'hover:bg-gray-50 border-2 border-transparent'
                          }`}
                          style={{ borderRadius: 'var(--radius-md)' }}
                        >
                          <span className="text-lg">{displayInfo.icon}</span>
                          
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-medium" style={{ fontSize: 'var(--text-sm)' }}>
                                {role.name}
                              </span>
                              <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${getColorClasses(displayInfo.badgeColor)}`}>
                                {displayInfo.badgeText}
                              </span>
                            </div>
                            
                            <p className="text-xs text-gray-600 mb-1 truncate">
                              {displayInfo.description}
                            </p>
                            
                            {displayInfo.specialty && (
                              <div className="text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded truncate">
                                {displayInfo.specialty}
                              </div>
                            )}
                          </div>

                          {currentRole === role.id && (
                            <div className="text-blue-600">✓</div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                </div>
              )}

              {/* 我的角色 */}
              <div className="p-4">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-semibold text-gray-700" style={{ fontSize: 'var(--text-sm)' }}>
                    我的角色 ({rolesData.custom.length}/5)
                  </h4>
                </div>
                
                {rolesData.custom.length > 0 ? (
                  <div className="space-y-2 mb-3">
                    {rolesData.custom.map(role => {
                      const displayInfo = getRoleDisplayInfo(role)
                      return (
                        <div
                          key={role.id}
                          onClick={() => {
                            onRoleChange(role.id)
                            setIsOpen(false)
                          }}
                          className={`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all ${
                            currentRole === role.id 
                              ? 'bg-blue-50 border-blue-200 border-2' 
                              : 'hover:bg-gray-50 border-2 border-transparent'
                          }`}
                          style={{ borderRadius: 'var(--radius-md)' }}
                        >
                          <span className="text-lg">{displayInfo.icon}</span>
                          
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-medium" style={{ fontSize: 'var(--text-sm)' }}>
                                {role.name}
                              </span>
                              <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${getColorClasses(displayInfo.badgeColor)}`}>
                                {displayInfo.badgeText}
                              </span>
                              {role.usage_count && role.usage_count > 0 && (
                                <span className="text-xs text-gray-500">
                                  {role.usage_count}次使用
                                </span>
                              )}
                            </div>
                            
                            <p className="text-xs text-gray-600 mb-1 truncate">
                              {displayInfo.description}
                            </p>
                            
                            {displayInfo.specialty && (
                              <div className="text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded truncate">
                                {displayInfo.specialty}
                              </div>
                            )}
                          </div>

                          {currentRole === role.id && (
                            <div className="text-blue-600">✓</div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                ) : (
                  <p className="text-sm text-gray-500 mb-3 text-center py-4">
                    还没有自定义角色
                  </p>
                )}

                {/* 创建角色按钮 */}
                {rolesData.custom.length < 5 && onCreateRole && (
                  <button
                    onClick={() => {
                      onCreateRole()
                      setIsOpen(false)
                    }}
                    className="w-full flex items-center justify-center gap-2 p-3 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all"
                    style={{ borderRadius: 'var(--radius-md)' }}
                  >
                    <span className="text-blue-600">➕</span>
                    <span className="text-sm font-medium text-blue-600">创建自定义角色</span>
                  </button>
                )}

                {rolesData.custom.length >= 5 && (
                  <div className="text-xs text-gray-500 text-center p-2 bg-yellow-50 rounded">
                    已达到5个角色上限，请删除不常用的角色
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      )}
    </div>
  )
}

// 紧凑版角色选择器（用于顶部栏）
export const CompactRoleSelector: React.FC<RoleSelectorProps> = ({
  currentRole,
  onRoleChange,
  onCreateRole,
  disabled = false,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [rolesData, setRolesData] = useState<RolesData>({ builtin: [], custom: [] })
  const [loading, setLoading] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  const currentRoleOption = [...rolesData.builtin, ...rolesData.custom].find(role => role.id === currentRole)

  // 加载角色数据
  useEffect(() => {
    const loadRoles = async () => {
      setLoading(true)
      try {
        const data = await fetchRoles()
        setRolesData(data)
      } catch (error) {
        console.error('Failed to load roles:', error)
      } finally {
        setLoading(false)
      }
    }
    
    loadRoles()
  }, [])

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const getColorClasses = (color: string = 'gray') => {
    const colorMap = {
      blue: 'bg-blue-100 text-blue-700',
      purple: 'bg-purple-100 text-purple-700',
      pink: 'bg-pink-100 text-pink-700',
      green: 'bg-green-100 text-green-700',
      orange: 'bg-orange-100 text-orange-700'
    }
    return colorMap[color as keyof typeof colorMap] || 'bg-gray-100 text-gray-700'
  }

  const getRoleDisplayInfo = (role: RoleOption) => {
    if (role.is_builtin) {
      return {
        icon: role.icon || '🤖',
        title: role.specialty || '',
        badgeText: '专家',
        badgeColor: role.color || 'blue'
      }
    } else {
      return {
        icon: '⚡',
        title: role.title || '',
        badgeText: '自定义',
        badgeColor: 'purple'
      }
    }
  }

  return (
    <div className={clsx('relative', className)} ref={dropdownRef}>
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled}
        className="flex items-center gap-3 px-4 py-2 rounded-lg border-2 bg-white transition-all hover:border-blue-300 hover:shadow-sm"
        style={{
          border: '2px solid var(--gray-200)',
          borderRadius: 'var(--radius-lg)',
          fontSize: 'var(--text-sm)'
        }}
      >
        {/* 角色信息 */}
        <div className="flex items-center gap-2">
          <span className="text-base">
            {currentRoleOption ? getRoleDisplayInfo(currentRoleOption).icon : '🤖'}
          </span>
          <div className="flex flex-col">
            <span className="font-medium">
              {currentRoleOption?.name || '选择角色'}
            </span>
            {currentRoleOption && getRoleDisplayInfo(currentRoleOption).title && (
              <span className="text-xs text-gray-500">
                {getRoleDisplayInfo(currentRoleOption).title}
              </span>
            )}
          </div>
          {currentRoleOption && (
            <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${getColorClasses(getRoleDisplayInfo(currentRoleOption).badgeColor)}`}>
              {getRoleDisplayInfo(currentRoleOption).badgeText}
            </span>
          )}
        </div>
        
        {/* 状态和箭头 */}
        <div className="flex items-center gap-2 ml-2">
          <div 
            className="w-2 h-2 rounded-full bg-green-500"
            title="角色已选择"
          />
          <span className="text-gray-400" style={{ fontSize: 'var(--text-xs)' }}>
            {isOpen ? '▲' : '▼'}
          </span>
        </div>
      </button>

      {isOpen && (
        <div className="absolute top-full right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-[250px]"
             style={{
               borderRadius: 'var(--radius-lg)',
               boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)'
             }}>
          {loading ? (
            <div className="p-4 text-center">
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mx-auto"></div>
              <p className="text-xs text-gray-500 mt-1">加载中...</p>
            </div>
          ) : (
            <div className="p-2">
              {/* 预设角色 */}
              {rolesData.builtin.length > 0 && (
                <>
                  <div className="px-2 py-1 text-xs font-semibold text-gray-500 border-b border-gray-100">
                    预设角色
                  </div>
                  {rolesData.builtin.map((role) => {
                    const displayInfo = getRoleDisplayInfo(role)
                    return (
                      <button
                        key={role.id}
                        onClick={() => {
                          onRoleChange(role.id)
                          setIsOpen(false)
                        }}
                        className={`w-full flex items-center gap-3 p-3 rounded-lg transition-all ${
                          currentRole === role.id 
                            ? 'bg-blue-50 text-blue-700' 
                            : 'hover:bg-gray-50'
                        }`}
                        style={{ borderRadius: 'var(--radius-md)' }}
                      >
                        <span>{displayInfo.icon}</span>
                        <div className="flex-1 text-left">
                          <span className="font-medium" style={{ fontSize: 'var(--text-sm)' }}>
                            {role.name}
                          </span>
                        </div>
                        <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${getColorClasses(displayInfo.badgeColor)}`}>
                          {displayInfo.badgeText}
                        </span>
                        {currentRole === role.id && (
                          <div className="text-blue-600">✓</div>
                        )}
                      </button>
                    )
                  })}
                </>
              )}

              {/* 我的角色 */}
              {rolesData.custom.length > 0 && (
                <>
                  <div className="px-2 py-1 text-xs font-semibold text-gray-500 border-b border-gray-100 mt-2">
                    我的角色 ({rolesData.custom.length}/5)
                  </div>
                  {rolesData.custom.map((role) => {
                    const displayInfo = getRoleDisplayInfo(role)
                    return (
                      <button
                        key={role.id}
                        onClick={() => {
                          onRoleChange(role.id)
                          setIsOpen(false)
                        }}
                        className={`w-full flex items-center gap-3 p-3 rounded-lg transition-all ${
                          currentRole === role.id 
                            ? 'bg-blue-50 text-blue-700' 
                            : 'hover:bg-gray-50'
                        }`}
                        style={{ borderRadius: 'var(--radius-md)' }}
                      >
                        <span>{displayInfo.icon}</span>
                        <div className="flex-1 text-left">
                          <span className="font-medium" style={{ fontSize: 'var(--text-sm)' }}>
                            {role.name}
                          </span>
                        </div>
                        <span className={`px-2 py-0.5 text-xs rounded-full font-medium ${getColorClasses(displayInfo.badgeColor)}`}>
                          {displayInfo.badgeText}
                        </span>
                        {currentRole === role.id && (
                          <div className="text-blue-600">✓</div>
                        )}
                      </button>
                    )
                  })}
                </>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  )
}